import React, { Component } from "react";
// 轮播图1.0：导入轮播图组件
import { Carousel } from "antd-mobile";
import { get_Swiper_Data } from "../../utils/http_biz";

import Search from "../Search";

class Swiper extends Component {
  state = {
    data: [],
    imgHeight: 176,
  };

  // 轮播图2.0：在状态对象中定义轮播图需要的数据
  async get_Swiper_Data() {
    let { body } = await get_Swiper_Data();
    this.setState({ data: body });
  }

  componentDidMount() {
    //   当页面加载完毕以后，获取轮播图图片数据更新到state中的data中
    this.get_Swiper_Data();
  }

  render() {
    return (
      <div>
        {/* 使用Search组件 */}
        <Search></Search>

        {this.state.data.length > 0 && (
          <Carousel
            autoplay={true} // 控制自动轮播的属性
            infinite // 加了这个属性就控制了无限轮播
            // 轮播前回调
            // beforeChange={(from, to) =>
            //   console.log(`slide from ${from} to ${to}`)
            // }
            // // 轮播后回调
            // afterChange={(index) => console.log("slide to", index)}
          >
            {this.state.data.length > 0 &&
              this.state.data.map((val) => (
                <a
                  key={val.id}
                  href="http://www.itheima.com"
                  style={{
                    display: "inline-block",
                    width: "100%",
                    height: this.state.imgHeight,
                  }}
                >
                  <img
                    src={`https://api-haoke-web.itheima.net${val.imgSrc}`}
                    alt=""
                    style={{ width: "100%", verticalAlign: "top" }}
                    onLoad={() => {
                      // fire window resize event to change height
                      window.dispatchEvent(new Event("resize"));
                      this.setState({ imgHeight: "auto" });
                    }}
                  />
                </a>
              ))}
          </Carousel>
        )}
      </div>
    );
  }
}

export default Swiper;
